<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="路段名称" prop="roadName">
        <el-select v-model="queryParams.roadName" placeholder="请选择路段名称" clearable filterable>
          <el-option
            v-for="dict in dict.type.sys_road"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="互通名称" prop="interchangeName">
        <el-input
          v-model="queryParams.interchangeName"
          placeholder="请输入互通名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['functiontest:RoadInterchangeTest:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['functiontest:RoadInterchangeTest:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['functiontest:RoadInterchangeTest:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleFieldAudit"
          v-hasPermi="['functiontest:RoadInterchangeTest:fieldAudit']"
        >实测单位审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleOwnerAudit"
          v-hasPermi="['functiontest:RoadInterchangeTest:ownerAudit']"
        >业主审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleCenterAudit"
          v-hasPermi="['functiontest:RoadInterchangeTest:centerAudit']"
        >中心审核</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="RoadInterchangeTestList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="父节点" prop="parentId" />
      <el-table-column label="路段名称" align="center" prop="roadName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_road" :value="scope.row.roadName"/>
        </template>
      </el-table-column>
      <el-table-column label="互通名称" align="center" prop="interchangeName" />
      <el-table-column label="车行方向1" align="center" prop="direction1" />
      <el-table-column label="车行方向2" align="center" prop="direction2" />
      <el-table-column label="匝道类型" align="center" prop="rampType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_ramp_length_type" :value="scope.row.rampType"/>
        </template>
      </el-table-column>
      <el-table-column label="匝道长度" align="center" prop="rampLength">
        <template slot-scope="scope">
          <span v-if="scope.row.rampLength">{{ scope.row.rampLength }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.image" :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['functiontest:RoadInterchangeTest:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['functiontest:RoadInterchangeTest:add']"
            v-if="!isThirdLevelNode(scope.row)"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['functiontest:RoadInterchangeTest:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改枢纽互通里程实测数据测试对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父节点" prop="parentId" v-if="formLevel === 1" v-show="false">
          <treeselect v-model="form.parentId" :options="RoadInterchangeTestOptions" :normalizer="normalizer" placeholder="请选择父节点" />
        </el-form-item>
        <el-form-item label="路段名称" prop="roadName" v-if="formLevel === 1">
          <el-select v-model="form.roadName" placeholder="请选择路段名称" filterable clearable>
            <el-option
              v-for="dict in dict.type.sys_road"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="互通名称" prop="interchangeName" v-if="formLevel === 2">
          <el-input v-model="form.interchangeName" placeholder="请输入互通名称" />
        </el-form-item>
        <el-form-item label="车行方向1" prop="direction1" v-if="formLevel === 3">
          <el-input v-model="form.direction1" placeholder="请输入车行方向1" />
        </el-form-item>
        <el-form-item label="车行方向2" prop="direction2" v-if="formLevel === 3">
          <el-input v-model="form.direction2" placeholder="请输入车行方向2" />
        </el-form-item>
        <el-form-item label="匝道类型" prop="rampType" v-if="formLevel === 3">
          <el-select v-model="form.rampType" placeholder="请选择匝道类型" filterable clearable>
            <el-option
              v-for="dict in dict.type.sys_ramp_length_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="匝道长度" prop="rampLength" v-if="formLevel === 3">
          <el-input v-model="form.rampLength" placeholder="请输入匝道长度" />
        </el-form-item>
        <el-form-item label="图片" prop="image" v-if="formLevel === 2">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark" v-if="formLevel === 3">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoadInterchangeTest, getRoadInterchangeTest, delRoadInterchangeTest, addRoadInterchangeTest, updateRoadInterchangeTest, exportRoadInterchangeTest, importRoadInterchangeTest, importTemplateRoadInterchangeTest, fieldAuditRoadInterchangeTestBatch, ownerAuditRoadInterchangeTestBatch, centerAuditRoadInterchangeTestBatch } from "@/api/functiontest/RoadInterchangeTest"
import Treeselect from "@riophae/vue-treeselect"
import ImagePreview from "@/components/ImagePreview"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { getUserProfile } from "@/api/system/user"

export default {
  name: "RoadInterchangeTest",
  dicts: ['sys_road', 'sys_ramp_length_type'],
  components: {
    Treeselect,
    ImagePreview
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 枢纽互通里程实测数据测试表格数据
      RoadInterchangeTestList: [],
      // 枢纽互通里程实测数据测试树选项
      RoadInterchangeTestOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        roadName: null,
        interchangeName: null,
        deptId: null,
        roleId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      deptId: '',
      roleId: '',
      // 表单层级：1-第一层，2-第二层，3-第三层
      formLevel: 1,
      // 上传参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + this.$store.getters.token },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/functiontest/RoadInterchangeTest/importData"
      }
    }
  },
  created() {
    this.getUser().then(() => {
      this.getList();
    });
  },
  methods: {
    getUser() {
      return getUserProfile().then(response => {
        if(response.data.roles[0].roleId != 1) {
          this.deptId = response.data.dept.deptId
        }else{
          this.deptId = null
        }
        this.roleId = response.data.roles[0].roleId
      })
    },
    /** 查询枢纽互通里程实测数据测试列表 */
    getList() {
      this.queryParams.deptId = this.deptId
      this.queryParams.roleId = this.roleId
      this.loading = true
      listRoadInterchangeTest(this.queryParams).then(response => {
        this.RoadInterchangeTestList = this.handleTree(response.data, "id", "parentId")
        // 添加调试信息
        
        this.loading = false
      })
    },
    /** 转换枢纽互通里程实测数据测试数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.roadName,
        children: node.children
      }
    },
	/** 查询枢纽互通里程实测数据测试下拉树结构 */
    getTreeselect() {
      listRoadInterchangeTest().then(response => {
        this.RoadInterchangeTestOptions = []
        const data = { id: 0, roadName: '顶级节点', children: [] }
        data.children = this.handleTree(response.data, "id", "parentId")
        this.RoadInterchangeTestOptions.push(data)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        roadName: null,
        interchangeName: null,
        direction1: null,
        direction2: null,
        rampType: null,
        rampLength: null,
        image: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row != null && row.id) {
        this.form.parentId = row.id
        // 判断节点层级
        if (row.parentId === 0) {
          // 从第一层节点新增第二层节点
          this.formLevel = 2
        } else {
          // 从第二层节点新增第三层节点
          this.formLevel = 3
        }
      } else {
        // 新增第一层节点
        this.form.parentId = 0
        this.formLevel = 1
      }
      this.open = true
      this.title = "添加枢纽互通里程实测数据测试"
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      if (row != null) {
        this.form.parentId = row.parentId
        // 判断节点层级
        if (row.parentId === 0) {
          // 第一层节点（顶级节点）
          this.formLevel = 1
        } else if (row.parentId !== 0 && !this.isThirdLevelNode(row)) {
          // 第二层节点：parentId不为0，但不是三级节点
          this.formLevel = 2
        } else {
          // 第三层节点
          this.formLevel = 3
        }
      }
      getRoadInterchangeTest(row.id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改枢纽互通里程实测数据测试"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRoadInterchangeTest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addRoadInterchangeTest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除枢纽互通里程实测数据测试编号为"' + row.id + '"的数据项？').then(function() {
        return delRoadInterchangeTest(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 判断是否为二级节点 */
    isSecondLevelNode(row) {
      // 二级节点的特征：parentId为0，表示它是顶级节点的直接子节点
      return row.parentId === 0;
    },
    /** 判断是否为三级节点 */
    isThirdLevelNode(row) {
      // 三级节点的特征：parentId不为0，且其父节点parentId不为0，表示它是三级节点
      // 需要在树结构中查找父节点来判断
      const findParent = (nodes, parentId) => {
        for (let node of nodes) {
          if (node.id === parentId) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const found = findParent(node.children, parentId);
            if (found) {
              return found;
            }
          }
        }
        return null;
      };
      
      // 查找当前行的父节点
      const parent = findParent(this.RoadInterchangeTestList, row.parentId);
      
      // 如果父节点存在且父节点的parentId不为0且不为null，则当前行是三级节点
      return parent && parent.parentId !== 0 && parent.parentId !== null;
    },
    /** 简单判断是否为三级节点（用于调试） */
    isThirdLevelNodeSimple(row) {
      // 简单判断：如果有图片且parentId不为0，则认为可能是三级节点
      return row.image && row.parentId !== 0;
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有枢纽互通里程实测数据测试项？').then(() => {
        return exportRoadInterchangeTest(queryParams);
      }).then(response => {
        this.download(response, '枢纽互通里程实测数据测试.xlsx');
      }).catch(() => {});
    },
    /** 下载文件 */
    download(data, fileName) {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    },
    
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "枢纽互通里程实测数据测试导入"
      this.upload.open = true
    },
    
    /** 下载模板操作 */
    importTemplate() {
      importTemplateRoadInterchangeTest().then(response => {
        this.download(response, '枢纽互通里程实测数据测试导入模板.xlsx')
      })
    },
    
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      // 导入成功后强制刷新树形结构，确保分层显示
      this.loading = true
      listRoadInterchangeTest(this.queryParams).then(response => {
        this.RoadInterchangeTestList = this.handleTree(response.data, "id", "parentId")
        this.loading = false
        // 自动展开所有节点，让用户看到分层效果
        this.$nextTick(() => {
          this.isExpandAll = true
          this.refreshTable = false
          this.$nextTick(() => {
            this.refreshTable = true
          })
        })
      })
    },
    
    /** 提交上传文件 */
    submitFileForm() {
      const file = this.$refs.upload.uploadFiles
      if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
        return
      }
      this.$refs.upload.submit()
    },
    
    /** 实测单位审核按钮操作 */
    handleFieldAudit() {
      this.$modal.confirm('是否确认对当前所有枢纽互通里程实测数据测试项进行实测单位审核？').then(() => {
        return fieldAuditRoadInterchangeTestBatch()
      }).then(response => {
        this.$modal.msgSuccess("实测单位批量审核成功")
        this.getList()
      }).catch(() => {})
    },
    
    /** 业主审核按钮操作 */
    handleOwnerAudit() {
      this.$modal.confirm('是否确认对当前所有枢纽互通里程实测数据测试项进行业主审核？').then(() => {
        return ownerAuditRoadInterchangeTestBatch({
          deptId: this.deptId,
          roleId: this.roleId
        })
      }).then(response => {
        this.$modal.msgSuccess("业主批量审核成功")
        this.getList()
      }).catch(() => {})
    },
    
    /** 中心审核按钮操作 */
    handleCenterAudit() {
      this.$modal.confirm('是否确认对当前所有枢纽互通里程实测数据测试项进行中心审核？').then(() => {
        return centerAuditRoadInterchangeTestBatch()
      }).then(response => {
        this.$modal.msgSuccess("中心批量审核成功")
        this.getList()
      }).catch(() => {})
    }
  }
}
</script>
